package cn.weiron.fun.sample.util;

import com.alibaba.excel.util.FileUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author weiRon
 * @version 1.0
 * @date 2022/9/26 16:33
 * @description
 */
public class DownloadUtil {


    /**
     * 下载文件
     * @param response
     * @param filePath
     * @param fileName
     */
    public static void downloadFile(HttpServletResponse response, String filePath, String fileName) {
        OutputStream responseStream = null;
        try {
            byte[] resultBytes = FileUtils.readFileToByteArray(new File(filePath));
            // response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            responseStream = response.getOutputStream();
            responseStream.write(resultBytes, 0, resultBytes.length);

            responseStream.flush();
            response.flushBuffer();
        } catch (Exception e) {
            if (null != responseStream) {
                try {
                    responseStream.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}
